package com.hunan.api.catv.action.member;

import com.hunan.api.catv.action.BaseAction;
import com.hunan.api.catv.annotation.MemberAuth;
import com.hunan.api.catv.common.Api;
import com.hunan.api.catv.common.CacheKey;
import com.hunan.api.catv.entity.Result;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.ResultCode;
import com.hunan.api.catv.entity.po.MemberShareRecord;
import com.hunan.api.catv.service.biz.member.MemberBiz;
import com.hunan.api.catv.service.biz.member.sign.MemberSigninRecordBiz;
import com.hunan.api.catv.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping(Api.m)
@Validated
public class MemberAction extends BaseAction {

    @Autowired
    MemberBiz memberBiz;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    MemberSigninRecordBiz memberSigninRecordBiz;

    @PostMapping("/login")
    public Result login(HttpServletRequest request, Integer loginType, String id, String sms, String ip, String phone, String pushToken) {
        return buildResult(memberBiz.login(loginType, id, sms, getRemoteIp(request), phone, pushToken));
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request, String refreshToken) {
        return buildServiceResult(memberBiz.logout(getMemberToken(request), refreshToken));
    }

    @MemberAuth
    @PostMapping("/update")
    public Result update(HttpServletRequest request, String nickName, MultipartFile headImg) {
        return buildResult(memberBiz.update(getMemberId(request), headImg, nickName));
    }

    @MemberAuth
    @GetMapping("/info")
    public Result info(HttpServletRequest request,boolean sensitive) {
        return buildResult(memberBiz.simple(getMemberId(request),sensitive));
    }

    @MemberAuth
    @GetMapping("/info/external/{phone}")
    public Result externalInfo(HttpServletRequest request,@PathVariable String phone) {
        return buildResult(memberBiz.simpleExternalInfo(getMemberId(request),phone));
    }


    @GetMapping("/refresh")
    public Result refresh(HttpServletRequest request, String refreshToken) {
        if (StringUtils.isEmpty(refreshToken)) {
            return buildRequire("refreshToken");
        }
        ServiceResult refreshResult = memberBiz.refresh(refreshToken);
        if (refreshResult.getStatus()) {
            return buildResult(refreshResult);
        }
        return new Result(ResultCode.unauthorized.getCode(), ResultCode.unauthorized.getMsg(), "");
    }

    @MemberAuth
    @PostMapping("/bind-cps")
    public Result bindCps(HttpServletRequest request, String smartCardCode) {
        return buildResultCode(memberBiz.bindCps(getMemberId(request), smartCardCode));
    }

    @MemberAuth
    @PostMapping("/unbind-cps")
    public Result unbindCps(HttpServletRequest request) {
        return buildResult(memberBiz.unbindCps(getMemberId(request)));
    }


    @PostMapping("/inviterRegist")
    public Result inviterRegist(HttpServletRequest request, String pushToken, String phone, String sms, Integer inviter) {
        return buildResult(memberBiz.inviterRegist(getRemoteIp(request), pushToken, phone, sms, inviter));
    }

    @PostMapping("/registLogin")
    public Result registLogin(HttpServletRequest request, String pushToken, String phone, String sms, String ticket) {

        return buildResult(memberBiz.registLogin(getRemoteIp(request), pushToken, phone, sms,ticket));
    }

    @MemberAuth
    @GetMapping("/inviterList")
    public Result inviterList(HttpServletRequest request, Integer pageNum, Integer pageSize) {
        return buildOK(memberBiz.inviterList(getMemberId(request), pageNum, pageSize), "");
    }

    @MemberAuth
    @GetMapping("/inviterCount")
    public Result inviterCount(HttpServletRequest request) {
        return buildOK(memberBiz.inviterCount(getMemberId(request)), "");
    }

    /**
     * 通过用户昵称获取用户信息
     *
     * @param name
     * @return
     */
    @GetMapping("/getMemberInfoByName/{name}")
    public Result getMemberInfoByName(@PathVariable("name") String name) {
        return buildOK(memberBiz.getMemberInfoByName(name), "");
    }

    /**
     * 通过手机号获取用户信息
     *
     * @param phone
     * @return
     */
    @GetMapping("/getMemberInfoByPhone/{phone}")
    public Result getMemberInfoByPhone(@PathVariable("phone") String phone) {
        return buildOK(memberBiz.getMemberInfoByPhone(phone), "");
    }

    /**
     * 获取用户信息
     *
     * @param memberId
     * @return
     */
    @GetMapping("/getMemberInfoByMemberId/{memberId}")
    public Result getMemberInfoByMemberId(@NotNull @PathVariable("memberId") Integer memberId) {
        return buildOK(memberBiz.getMemberInfoByMemberId(memberId), "");
    }

    /**
     * 校验用户是否绑定微信
     */
    @MemberAuth
    @GetMapping("/checkMemberBindWx")
    public Result checkMemberBindWx(HttpServletRequest request) {
        return buildOK(memberBiz.checkMemberBindWx(getMemberId(request)), "");
    }

    /**
     * 校验用户是否是邀请注册登录
     */
    @MemberAuth
    @GetMapping("/checkMemberInviteRegister")
    public Result checkMemberInviteRegister(HttpServletRequest request) {
        return buildOK(memberBiz.checkMemberInviteRegister(getMemberId(request)), "");
    }

    /**
     * 通过openId获取用户信息
     *
     * @param openId
     * @return
     */
    @GetMapping("/getMemberInfoByOpenId/{openId}")
    public Result getMemberInfoByOpenId(@NotNull @PathVariable("openId") String openId) {
        return buildOK(memberBiz.getMemberInfoByOpenId(openId), "");
    }

    @MemberAuth
    @PostMapping("/bindWechat")
    public Result bindPhone(String id, HttpServletRequest request) {
        return buildResult(memberBiz.bindWechat(id, getMemberIdV2(request)));
    }

    //    @MemberAuth
    @GetMapping("/signin")
    public Result signin(String token, HttpServletRequest request) {
        log.info("签到接口，参数：[{}]-[{}]-[{}]", getRemoteIp(request), token, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHssmm")));
        Boolean isNotRequest = redisUtils.setNX("signin" + token, "1", 5, TimeUnit.SECONDS);
        if (!isNotRequest) {
            return buildFail(false, "操作太频繁！");
        }
        Result tokenResult = checkToken(token, request);
        if (tokenResult != null) {
            return tokenResult;
        }
        return buildResult(memberSigninRecordBiz.signin(getMemberId(request)));
    }

    //    @MemberAuth
    @GetMapping("/signinRecord")
    public Result signinRecord(String token, HttpServletRequest request) {
        Result tokenResult = checkToken(token, request);
        if (tokenResult != null) {
            return tokenResult;
        }
        return buildOK(memberSigninRecordBiz.signinRecord(getMemberId(request)), "");
    }


    @PostMapping("/inviterPlatinumIsland")
    public Result inviterPlatinumIsland(HttpServletRequest request, String pushToken, String phone, String sms, Integer inviter) {
        log.info("签到接口，参数：[{}]-[{}]-[{}]-[{}]", getRemoteIp(request), inviter, phone, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHssmm")));
        Boolean isNotRequest = redisUtils.setNX("inviterPlatinumIsland_" + inviter, "1", 5, TimeUnit.SECONDS);
        if (!isNotRequest) {
            return buildFail(false, "操作太频繁！");
        }
        return buildResult(memberBiz.inviterPlatinumIsland(getRemoteIp(request), pushToken, phone, sms, inviter));
    }

    @MemberAuth
    @PostMapping("/visitPlatinumIsland")
    public Result visitPlatinumIsland(HttpServletRequest request) {
        return buildResult(memberSigninRecordBiz.visitPlatinumIsland(getMemberId(request)));
    }


    private Result checkToken(String token, HttpServletRequest request) {
        if (StringUtils.isEmpty(token)) {
            return new Result(ResultCode.unauthorized.getCode(), ResultCode.unauthorized.getMsg(), "");
        } else {
            String token_key = MessageFormat.format(CacheKey.memberToken, token);
            Object token_result = redisUtils.get(token_key);
            if (ObjectUtils.isEmpty(token_result)) {
                log.debug("[member login token:{} isEmpty] ", token_key);
                return new Result(ResultCode.invalid_token.getCode(), ResultCode.invalid_token.getMsg(), "");
            }
            //token未过期，通过验证
            request.setAttribute("memberId", token_result);
        }
        return null;
    }

    @MemberAuth
    @PostMapping("/bindTVAccount")
    public Result bindTVAccount(String passport, HttpServletRequest request) {
        return buildResult(memberBiz.bindTVAccount(passport, getMemberId(request)));
    }

    @MemberAuth
    @GetMapping("/getTVBindState")
    public Result getTVBindState(HttpServletRequest request) {
        return buildResult(memberBiz.getTVBindState(getMemberId(request)));
    }

    @MemberAuth
    @GetMapping("/totalPlatinumIslandIncome")
    public Result getMemberTotalPlatinumIsland(HttpServletRequest request) {
        return buildResult(memberBiz.getMemberTotalPlatinumIsland(getMemberId(request)));
    }

    @MemberAuth
    @GetMapping("/getPlatinumIslandInviteList")
    public Result getPlatinumIslandInviteList(HttpServletRequest request) {
        return buildResult(memberSigninRecordBiz.getPlatinumIslandInviteList(getMemberId(request)));
    }

    @PostMapping("/share/add")
    public Result addShare(HttpServletRequest request,@Valid MemberShareRecord memberShareRecord) {
        return buildResult(memberSigninRecordBiz.addShare(getMemberIdV2(request),memberShareRecord));
    }

}
